package com.dayanxs.Controller;

import com.dayanxs.Service.FileUploadService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/upload")
public class ImageUploadController {

    private final FileUploadService fileUploadService;

    public ImageUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }
    @Value("${file.api.url}")
    private String fileApiUrl;

    @PostMapping("/images")
    public ResponseEntity<?> uploadImage(@RequestPart("file") MultipartFile file) {
        try {
            // 上传文件并获取文件路径
            String filePath = fileUploadService.uploadImage(file);

            // 返回 JSON 格式响应
            Map<String, String> response = new HashMap<>();
            response.put("message", "文件上传成功！");
            response.put("filePath", fileApiUrl + filePath); // 生成 URL

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) { // 处理无效文件名或扩展名
            return ResponseEntity.status(201).body(Map.of("error", "无效文件: " + e.getMessage()));
        } catch (IOException e) { // 处理文件上传错误
            return ResponseEntity.status(201).body(Map.of("error", "上传文件时发生错误：" + e.getMessage()));
        }
    }
}
